package com.deYang.app.ljodfh.ui.activities;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.deYang.app.ljodfh.R;
import com.deYang.app.ljodfh.base.BaseCanPlayActivity;
import com.deYang.app.ljodfh.base.Constances;
import com.deYang.app.ljodfh.beans.ADynamicsItem;
import com.deYang.app.ljodfh.beans.AFileItem;
import com.deYang.app.ljodfh.beans.AHomePageItem;
import com.deYang.app.ljodfh.beans.FProgramme;
import com.deYang.app.ljodfh.beans.Titles;
import com.deYang.app.ljodfh.http.AbsNetCallBack;
import com.deYang.app.ljodfh.http.NetUtils;
import com.deYang.app.ljodfh.ui.adapter.AnchorHomePageAdapter;
import com.deYang.app.ljodfh.ui.util.IListShowData;
import com.deYang.app.ljodfh.ui.utils.GPlayerBottomControllerImp;
import com.deYang.app.ljodfh.ui.utils.GSFPlayerScreenControllImp;
import com.deYang.app.ljodfh.ui.utils.SkipUtil;
import com.deYang.app.ljodfh.ui.utils.TitleUtils;
import com.deYang.app.ljodfh.ui.widget.BasePlayerView;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class AnchorHomePageActivity extends BaseCanPlayActivity implements CanRefreshLayout.OnRefreshListener
        , CanRefreshLayout.OnLoadMoreListener, CanRefreshLayout.IScrollView {
    //    @ViewInject(R.id.title_red_base)
//    private ViewGroup title_lay;
    @BindView(R.id.anchor_home_refreshLayout)
    protected CanRefreshLayout refreshLayout;
    //    @BindView(R.id.can_content_view)
//    protected CustomLinearLayout detail;
    @BindView(R.id.anchor_home_page_ll)
    protected LinearLayout top_ll;
    //    @ViewInject(R.id.app_bar)
//    private AppBarLayout appBarLayout;
//    @ViewInject(R.id.toolbar_layout)
//    private CollapsingToolbarLayout collapsingToolbarLayout;
//    @ViewInject(R.id.anchor_home_page_img)
//    private CustomEXImageView img;
//    @ViewInject(R.id.anchor_home_page_toolbar)
//    private Toolbar toolbar;
//    @ViewInject(R.id.anchor_home_page_title)
//    private CustomFontTextView titleTx;
    @BindView(R.id.can_content_view)
    protected CustomLinearLayout detail;
    @BindView(R.id.anchor_home_page_list)
    protected RecyclerView recyclerView;
//    @BindView(R.id.anchor_home_video_container)
//    protected AbsoluteLayout videoContainer;

    private String titleStr;
    private AnchorHomePageAdapter adapter;
    private LinearLayoutManager manager;
    private String homePageUrl;
    private int currentPage = 0;
    private int pageAll;
    private GPlayerBottomControllerImp bottomController;
    private GSFPlayerScreenControllImp screenControllImp;
    private String contentVideoUrl;
    private ADynamicsItem dynamicsTemp;
    private int tempPos;
    private int height;

    private BasePlayerView videoPlayers;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        isVideoTop = false;
        homePageUrl = getIntent().getStringExtra(EX_URL);
        titleStr = getIntent().getStringExtra(EX_TITLE);
        initViews();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_anchor_home_page);
        ButterKnife.bind(this);
    }

    @NonNull
    @Override
    protected BasePlayerView createdPlayerView() {
        if (videoPlayers == null) {
            videoPlayers = new BasePlayerView(this);
        }
        return videoPlayers;
    }

    @Override
    protected StandardGSYVideoPlayer getVideoPlayer() {
        return videoPlayers;
    }

    private void initViews() {
        final int pa = getResources().getDimensionPixelOffset(R.dimen.divider_shadow_margin_bottom);
        top_ll.postDelayed(new Runnable() {
            @Override
            public void run() {
                height = top_ll.getHeight() + pa;
            }
        }, 300);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(manager);
        detail.setiScrollView(this);
        refreshLayout.autoRefresh();

    }

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
        } else {
            currentPage = currentPage + 1;
            if (currentPage < pageAll) {
                getAHomePageList(currentPage);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SkipUtil.REQUEST_CODE_PLAY_BASE) {
            if (data == null || refreshLayout.isRefreshing() || adapter == null) {
                return;
            }
            int itemPos = data.getIntExtra(SkipUtil.EX_POS_ITEM, -1);
            if (itemPos >= 0) {
                ADynamicsItem item = (ADynamicsItem) adapter.getItem(itemPos);
                if (item != null) {
                    if (resultCode == RESULT_OK) {
                        item.setCurrentPos(0);
                    } else {
                        item.setCurrentPos(data.getIntExtra(SkipUtil.EX_POS, 0));
                    }
                }
            }
        }
    }

    @Override
    public void onRefresh() {
        currentPage = 0;
        getAHomePageList(currentPage);
    }

    @Override
    protected void onDestroy() {
        if (floatVideoUtils != null) {
            recyclerView.removeOnScrollListener(floatVideoUtils.getRecyclerScrollListener());
        }
        super.onDestroy();
    }

    private void getAHomePageList(int calledPage) {
        if (TextUtils.isEmpty(homePageUrl)) {
            toast("数据错误");
            return;
        }
        NetUtils.getNetAdapter().getAHomePageList(getOwnerName(), homePageUrl, calledPage
                , new AbsNetCallBack<AHomePageItem>(AHomePageItem.class, calledPage) {
                    @Override
                    public void onSuc(AHomePageItem aHomePageItem) {
                        // JLog.e("====data==" + aHomePageItem);
                        if (aHomePageItem != null) {
                            pageAll = aHomePageItem.getPageAll();
                            currentPage = aHomePageItem.getPageIndex();
                            setPageData(aHomePageItem);
                        }
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        onNetFinish();
                    }
                });
    }

    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.loadMoreComplete();
        }
        refreshLayout.setLoadMoreEnabled(currentPage + 1 < pageAll);
    }

    private void setPageData(AHomePageItem data) {
        List<IListShowData> list = new ArrayList<>();
        List<FProgramme> programList = data.getProgramList();
        List<ADynamicsItem> dynamics = data.getAnchorDynamic();
        AFileItem anchorInfo = data.getAnchorInfo();
        if (anchorInfo != null) {
            anchorInfo.setViewType(AnchorHomePageAdapter.VIEWTYPE_FILE);
            list.add(anchorInfo);
        }
        Titles titles = null;
        if (ListUtils.isListValued(programList)) {
            titles = new Titles();
            titles.setTitle(getString(R.string.anchor_column));
            titles.setViewType(AnchorHomePageAdapter.VIEWTYPE_TITLE);
            list.add(titles);
            for (FProgramme program : programList) {
                program.setViewType(AnchorHomePageAdapter.VIEWTYPE_COLUMN);
            }
            list.addAll(programList);
        }
        if (ListUtils.isListValued(dynamics)) {
            titles = new Titles();
            titles.setTitle(getString(R.string.anchor_dynamics));
            titles.setViewType(AnchorHomePageAdapter.VIEWTYPE_TITLE);
            list.add(titles);
            for (ADynamicsItem dynamicsItem : dynamics) {
//                dynamicsItem.setCoverImage("/sctv/1/image/public/201708/20170828112101_pex8ecr7nr.jpg");
//                dynamicsItem.setContentVideo("http://baobab.wdjcdn.com/1455969783448_5560_854x480.mp4");
                dynamicsItem.setViewType(AnchorHomePageAdapter.VIEWTYPE_DYNAMICS);
            }
            list.addAll(dynamics);
        }
        if (currentPage == 0) {
            if (adapter == null) {
                adapter = new AnchorHomePageAdapter(this, list);
                adapter.setInAnchorDetail(true);
                adapter.setPlayClick(playOnItemClick);
                recyclerView.setAdapter(adapter);
            } else {
                adapter.setData(list);
            }
        } else {
            adapter.addDatas(list);
        }
    }


//    private void playVideo(View topImg, String url, String title, int pos) {
//        int netType = NetModeUtil.GetNetype(this);
//        JLog.e("netType=" + netType);
//        if (TextUtils.isEmpty(url)) {
//            toast(R.string.loading_invalid_data);
//            return;
//        }
//
//        if (initFloatVideoUtils(topImg, videoContainer, height)) {
//            recyclerView.addOnScrollListener(floatVideoUtils.getRecyclerScrollListener());
//        }
//        JLog.e("netType=" + netType);
    // if (netType == 1) {   //wifi情况下直接播放
//        floatVideoUtils.setLiving(false).play(topImg, url);
    //   floatVideoUtils.play(topImg, url, title, true);
//        if (videoPlayers == null) {
//            floatVideoUtils.showPlayer(topImg, false);
//        }
//        videoPlayers.setUp(url, false, title);
//        if (pos > 0) {
//            videoPlayers.setPlayPosition(pos);
//        }
//        videoPlayers.startPlay();
//        } else {
//            showNetDialog();   //无WiFi情况下弹框提示
//        }
//    }

    OnItemInternalClick playOnItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            if (floatVideoUtils != null && floatVideoUtils.isShowing()) {
                int currentPos = 0;
//                        floatVideoUtils.getPlayerView().getCurrentPosition();
                dynamicsTemp = (ADynamicsItem) adapter.getItem(tempPos);
                dynamicsTemp.setCurrentPos(currentPos / 1000);
            }
            ADynamicsItem dynamics = (ADynamicsItem) adapter.getItem(position);
            contentVideoUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, dynamics.getContentVideo());
            playView = view;
            toVideoPlay(contentVideoUrl, dynamics.getCurrentPos(), position);
//            if (dynamics.getCurrentPos() != 0) {
//                playVideo(view, contentVideoUrl, dynamics.getDataTitle(), dynamics.getCurrentPos() * 1000);
////                floatVideoUtils.startPlay();
//            } else {
//                playVideo(view, contentVideoUrl, dynamics.getDataTitle(), 0);
//            }

            tempPos = position;
        }
    };

    @Override
    protected void onChangedToLandscape(Configuration newConfig) {
        super.onChangedToLandscape(newConfig);
//        if (title_lay != null) {
//            title_lay.setVisibility(View.GONE);
//        }
    }

    @Override
    protected void onChangedToPortrait(Configuration newConfig) {
        super.onChangedToPortrait(newConfig);
//        if (title_lay != null) {
//            title_lay.setVisibility(View.VISIBLE);
//        }
//        if (floatVideoUtils != null) {
//            mHandler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    floatVideoUtils.refreshVideoLocation();
//                }
//            }, 200);
//        }
    }

    private void toVideoPlay(String url, int pos, int itemPos) {
        SkipUtil.skipToVideoPlay(this, url, pos, itemPos);
    }

    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(recyclerView, -1);
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(recyclerView, 1);
    }
}

